﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsTest
{
    public partial class StockForm : Form
    {
        private Timer timer;
        public StockForm()
        {
            InitializeComponent();
            timer = new Timer();
            timer.Tick += timer_Tick;
            timer.Interval = 1000;
            timer.Start();
        }

        List<StockInfo> list = new List<StockInfo>();

        private void LoadData()
        {
            if (list == null || list.Count <= 0) return;
            var requestUrl = "http://hq.sinajs.cn/list=" + string.Join(",", list.Select(x => x.SecuCode).Distinct());
            var resultStr = TestBll.DoPost(requestUrl, "");
            var ls = resultStr.Split(new string[] { ";\n" }, StringSplitOptions.RemoveEmptyEntries);

            list.ForEach(x =>
            {
                string mt = string.Format("var hq_str_{0}=\"", x.SecuCode);
                string el = ls.FirstOrDefault(k => k.Contains(mt));
                if (!string.IsNullOrEmpty(el))
                {
                    x.IsValid = true;
                    el = el.Replace(mt, "").Replace("\"", "");
                    if (string.IsNullOrEmpty(el))
                    {
                        x.IsValid = false;
                        return;
                    }
                    var lst = el.Split(',');
                    if (lst == null || lst.Length < 6)
                    {
                        x.IsValid = false;
                        return;
                    }
                    x.SecuName = lst[0];
                    x.ClosePrice = Convert.ToDecimal(lst[2]);
                    x.Price = Convert.ToDecimal(lst[3]);
                    x.MinPrice = Convert.ToDecimal(lst[5]);
                    x.MaxPrice = Convert.ToDecimal(lst[4]);
                    x.CF = Convert.ToInt32((x.Price - x.BuyPrice) * x.StockNum);
                    if (x.BuyDate < DateTime.Now.Date)
                    {
                        x.TF = Convert.ToInt32((x.Price - x.ClosePrice) * x.StockNum);
                    }
                    else
                    {
                        x.TF = Convert.ToInt32((x.Price - x.BuyPrice) * x.StockNum);
                    }
                    if (x.BuyPrice != 0)
                        x.F = Convert.ToDecimal((((x.Price - x.BuyPrice) / x.BuyPrice) * 100).ToString("0.00"));
                    x.FStr = x.F.ToString("0.00");
                    x.PriceStr = x.Price.ToString("0.00");
                }
            });
            LoadGVData();
        }

        private void LoadGVData()
        {
            list = list.Where(x => x.IsValid).ToList();
            dgv_StockInfo.DataSource = list;
            dgv_StockInfo.Refresh();
            this.Text = list.Sum(x => x.CF).ToString();
        }

        void timer_Tick(object sender, EventArgs e)
        {
            LoadData();
        }

        private void btn_Add_Click(object sender, EventArgs e)
        {
            timer.Stop();
            string code = txt_SecuCode.Text;
            if (string.IsNullOrEmpty(code) || code.Length < 6)
            {
                MessageBox.Show("Code非法");
                timer.Start();
                return;
            }
            if (code.Length == 6)
            {
                string f = "sz";
                if (code.StartsWith("6"))
                {
                    f = "sh";
                }
                code = f + code;
            }
            string p = txt_Price.Text;
            if (string.IsNullOrEmpty(p) || p == "价格") p = "0";
            string n = txt_StockNum.Text;
            if (string.IsNullOrEmpty(n) || n == "数量") n = "0";

            list.Add(new StockInfo() { SecuCode = code, BuyPrice = Convert.ToDecimal(p), StockNum = Convert.ToInt32(n), BuyDate = DateTime.Now });

            timer.Start();
        }

        string path = "d://stock/";
        string fileName = "stockinfo.txt";
        private void ReadStock()
        {
            string str = File.ReadAllText(path + fileName, Encoding.UTF8);
            if (!string.IsNullOrEmpty(str))
            {
                list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<StockInfo>>(str);
            }
        }

        private void SaveStock()
        {
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            if (list != null && list.Count > 0)
                File.WriteAllText(path + fileName, Newtonsoft.Json.JsonConvert.SerializeObject(list), Encoding.UTF8);
            else
                File.WriteAllText(path + fileName, "");
        }

        private void StockForm_Load(object sender, EventArgs e)
        {
            ReadStock();
        }

        private void StockForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            SaveStock();
        }

        private void txt_SecuCode_MouseHover(object sender, EventArgs e)
        {
            string d = txt_SecuCode.Text.Trim();
            if (d == "000001")
            {
                txt_SecuCode.Text = "";
            }
        }

        private void txt_SecuCode_MouseLeave(object sender, EventArgs e)
        {
            string d = txt_SecuCode.Text.Trim();
            if (string.IsNullOrEmpty(d))
            {
                txt_SecuCode.Text = "000001";
            }
        }

        private void txt_StockNum_MouseHover(object sender, System.EventArgs e)
        {
            string d = txt_StockNum.Text.Trim();
            if (d == "数量")
            {
                txt_StockNum.Text = "";
            }
        }

        private void txt_StockNum_MouseLeave(object sender, System.EventArgs e)
        {
            string d = txt_StockNum.Text.Trim();
            if (string.IsNullOrEmpty(d))
            {
                txt_StockNum.Text = "数量";
            }
        }

        private void txt_Price_MouseHover(object sender, System.EventArgs e)
        {
            string d = txt_Price.Text.Trim();
            if (d == "价格")
            {
                txt_Price.Text = "";
            }
        }

        private void txt_Price_MouseLeave(object sender, System.EventArgs e)
        {
            string d = txt_Price.Text.Trim();
            if (string.IsNullOrEmpty(d))
            {
                txt_Price.Text = "价格";
            }
        }

        private void btn_Delete_Click(object sender, EventArgs e)
        {
            var code = btn_Delete.Tag.ToString();
            list = list.Where(x => x.SecuCode != code).ToList();
            btn_Delete.Visible = false;
        }

        private void dgv_StockInfo_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
            {
                btn_Delete.Visible = false;
                return;
            }
            btn_Delete.Visible = true;
            int x = GetX(e.ColumnIndex);
            int y = GetY(e.RowIndex);
            btn_Delete.Tag = list[e.RowIndex].SecuCode;
            btn_Delete.Location = new Point(x, y);
        }

        int GetX(int c)
        {
            int x = 0;
            for (var i = 0; i <= c; i++)
            {
                x += dgv_StockInfo.Columns[i].Width;
            }
            return x;
        }

        int GetY(int r)
        {
            int y = dgv_StockInfo.Location.Y;
            for (var i = 0; i <= r; i++)
            {
                y += dgv_StockInfo.Rows[i].Height;
            }
            return y;
        }

        void StockForm_MouseLeave(object sender, System.EventArgs e)
        {
            btn_Delete.Visible = false;
        }

        private void btn_Download_Click(object sender, EventArgs e)
        {
            DownloadForm df = new DownloadForm();
            df.Show();
        }
    }
}
